#include "TaskEditDialog.h"
#include "TimePickerDialog.h"
#include <QVBoxLayout>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QMessageBox>
#include <QLabel>
#include <QUuid>
#include <QEventLoop>
#include <QDialog>
#include <QTimer>
#include <QScrollArea>

TaskEditDialog::TaskEditDialog(QWidget *parent)
    : FramelessWindow(parent)
    , m_isNewTask(true)
    , m_titleEdit(new QLineEdit(this))
    , m_statusCombo(new QComboBox(this))
    , m_descEdit(new QTextEdit(this))
    , m_startTimeEdit(new QDateTimeEdit(this))
    , m_endTimeEdit(new QDateTimeEdit(this))
    , m_reminderCheckBox(new QCheckBox("启用提醒", this))
    , m_reminderTimeEdit(new QDateTimeEdit(this))
    , m_dodEdit(new QTextEdit(this))
    , m_dodCharCountLabel(new QLabel("0/5 字符", this))
    , m_blockersEdit(new QTextEdit(this))
    , m_artifactsSummaryEdit(new QTextEdit(this))
    , m_artifactsLinksEdit(new QTextEdit(this))
    , m_dodTemplateBtn(new QPushButton("📋 DoD 模板", this))
    , m_saveBtn(new QPushButton("保存", this))
    , m_cancelBtn(new QPushButton("取消", this))
{
    setupUi();

    // 设置窗口为模态
    setWindowModality(Qt::ApplicationModal);

    // 强制为独立的顶级窗口/对话框，不随父窗口移动
    setWindowFlags(windowFlags() | Qt::Window | Qt::Dialog | Qt::FramelessWindowHint);

    // 设置默认值
    QDateTime now = QDateTime::currentDateTime();
    m_startTimeEdit->setDateTime(now);
    m_endTimeEdit->setDateTime(now.addSecs(3600));  // 默认1小时后结束
    m_reminderTimeEdit->setDateTime(now.addSecs(-600));  // 默认开始前10分钟提醒
}

TaskEditDialog::TaskEditDialog(const PlanTask& task, QWidget *parent)
    : FramelessWindow(parent)
    , m_task(task)
    , m_isNewTask(false)
    , m_titleEdit(new QLineEdit(this))
    , m_statusCombo(new QComboBox(this))
    , m_descEdit(new QTextEdit(this))
    , m_startTimeEdit(new QDateTimeEdit(this))
    , m_endTimeEdit(new QDateTimeEdit(this))
    , m_reminderCheckBox(new QCheckBox("启用提醒", this))
    , m_reminderTimeEdit(new QDateTimeEdit(this))
    , m_dodEdit(new QTextEdit(this))
    , m_dodCharCountLabel(new QLabel("0/5 字符", this))
    , m_blockersEdit(new QTextEdit(this))
    , m_artifactsSummaryEdit(new QTextEdit(this))
    , m_artifactsLinksEdit(new QTextEdit(this))
    , m_dodTemplateBtn(new QPushButton("📋 DoD 模板", this))
    , m_saveBtn(new QPushButton("保存", this))
    , m_cancelBtn(new QPushButton("取消", this))
{
    setupUi();

    // 设置窗口为模态
    setWindowModality(Qt::ApplicationModal);

    // 强制为独立的顶级窗口/对话框，不随父窗口移动
    setWindowFlags(windowFlags() | Qt::Window | Qt::Dialog | Qt::FramelessWindowHint);

    loadTask(task);
}

TaskEditDialog::~TaskEditDialog()
{
}

void TaskEditDialog::setupUi()
{
    setWindowTitle(m_isNewTask ? "新建任务" : "编辑任务");
    setMinimumSize(700, 680);  // [FDD-2025-11] 增加高度以容纳新字段
    
    // 创建主背景 widget（修复 FramelessWindow 透明背景问题）
    QWidget* backgroundWidget = new QWidget(this);
    backgroundWidget->setObjectName("backgroundWidget");
    backgroundWidget->setStyleSheet(
        "QWidget#backgroundWidget { "
        "  background-color: #2b2b2b; "
        "  border-radius: 8px; "
        "}"
    );
    
    // 设置深色主题样式
    setStyleSheet(
        "QWidget { "
        "  background-color: transparent; "  // 顶层透明，由 backgroundWidget 提供背景
        "  color: #e0e0e0; "
        "}"
        "QLabel { "
        "  color: #e0e0e0; "
        "  background-color: transparent; "
        "}"
        "QLineEdit, QTextEdit, QDateTimeEdit { "
        "  background-color: #3c3c3c; "
        "  border: 1px solid #555; "
        "  border-radius: 4px; "
        "  padding: 6px; "
        "  color: #e0e0e0; "
        "}"
        "QPushButton { "
        "  background-color: #3c3c3c; "
        "  border: 1px solid #555; "
        "  border-radius: 4px; "
        "  padding: 8px 16px; "
        "  color: #e0e0e0; "
        "}"
        "QPushButton:hover { "
        "  background-color: #4a4a4a; "
        "}"
        "QGroupBox { "
        "  color: #e0e0e0; "
        "  border: 1px solid #3c3c3c; "
        "  border-radius: 4px; "
        "  margin-top: 10px; "
        "  padding-top: 10px; "
        "  background-color: transparent; "
        "}"
    );
    
    // 创建标题栏
    QWidget* titleBar = new QWidget(backgroundWidget);
    titleBar->setObjectName("titleBar");
    titleBar->setFixedHeight(40);
    titleBar->setStyleSheet(
        "QWidget#titleBar { "
        "  background-color: #1e1e1e; "
        "  border-top-left-radius: 8px; "
        "  border-top-right-radius: 8px; "
        "}"
    );
    
    QHBoxLayout* titleLayout = new QHBoxLayout(titleBar);
    titleLayout->setContentsMargins(15, 0, 15, 0);
    
    QLabel* titleLabel = new QLabel(m_isNewTask ? "新建任务" : "编辑任务", titleBar);
    titleLabel->setStyleSheet("color: #e0e0e0; font-weight: bold; font-size: 14px; background-color: transparent;");
    titleLayout->addWidget(titleLabel);
    titleLayout->addStretch();
    
    // 设置标题栏为可拖拽区域
    setTitlebarWidgets({titleBar, titleLabel});
    
    // backgroundWidget 的布局（包含标题栏和内容）
    QVBoxLayout* backgroundLayout = new QVBoxLayout(backgroundWidget);
    backgroundLayout->setContentsMargins(0, 0, 0, 0);
    backgroundLayout->setSpacing(0);
    backgroundLayout->addWidget(titleBar);
    
    // 顶层容器布局（放置 backgroundWidget）
    QVBoxLayout* containerLayout = new QVBoxLayout(this);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->addWidget(backgroundWidget);
    
    // 内容区域
    QWidget* contentWidget = new QWidget();
    contentWidget->setStyleSheet("background-color: transparent;");
    QVBoxLayout* mainLayout = new QVBoxLayout(contentWidget);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea(backgroundWidget);
    scrollArea->setWidget(contentWidget);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setStyleSheet("QScrollArea { background-color: transparent; border: none; }");

    // 重新设置成员 widget 的父对象（构造函数中默认为 this）
    m_titleEdit->setParent(contentWidget);
    m_statusCombo->setParent(contentWidget);
    m_descEdit->setParent(contentWidget);
    m_dodEdit->setParent(contentWidget);
    m_dodCharCountLabel->setParent(contentWidget);
    m_blockersEdit->setParent(contentWidget);
    m_artifactsSummaryEdit->setParent(contentWidget);
    m_artifactsLinksEdit->setParent(contentWidget);
    m_dodTemplateBtn->setParent(contentWidget);
    m_startTimeEdit->setParent(contentWidget);
    m_endTimeEdit->setParent(contentWidget);
    m_reminderCheckBox->setParent(contentWidget);
    m_reminderTimeEdit->setParent(contentWidget);
    m_saveBtn->setParent(contentWidget);
    m_cancelBtn->setParent(contentWidget);

    // 表单布局
    QFormLayout* formLayout = new QFormLayout();
    formLayout->setSpacing(10);

    // 标题
    m_titleEdit->setPlaceholderText("请输入任务标题...");
    formLayout->addRow("标题*:", m_titleEdit);

    // [FDD-2025-11] 状态选择
    m_statusCombo->addItem("待办", static_cast<int>(TaskStatus::Todo));
    m_statusCombo->addItem("进行中", static_cast<int>(TaskStatus::Doing));
    m_statusCombo->addItem("已完成", static_cast<int>(TaskStatus::Done));
    m_statusCombo->addItem("已阻塞", static_cast<int>(TaskStatus::Blocked));
    m_statusCombo->addItem("已归档", static_cast<int>(TaskStatus::Archived));
    m_statusCombo->setCurrentIndex(0);  // 默认"待办"
    connect(m_statusCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &TaskEditDialog::onStatusChanged);
    formLayout->addRow("状态:", m_statusCombo);

    // 范围/描述
    m_descEdit->setPlaceholderText("任务范围/描述（可选）...");
    m_descEdit->setMaximumHeight(60);
    formLayout->addRow("范围/描述:", m_descEdit);

    // [FDD-2025-11] 完成定义（DoD）
    m_dodEdit->setPlaceholderText("描述任务的完成标准（至少5个字符）...");
    m_dodEdit->setMaximumHeight(80);
    connect(m_dodEdit, &QTextEdit::textChanged, this, [this]() {
        int charCount = m_dodEdit->toPlainText().length();
        m_dodCharCountLabel->setText(QString("%1/5 字符").arg(charCount));
        m_dodCharCountLabel->setStyleSheet(charCount >= 5 ? "color: #4CAF50;" : "color: #f44336;");
    });

    QHBoxLayout* dodLayout = new QHBoxLayout();
    QVBoxLayout* dodInputLayout = new QVBoxLayout();
    dodInputLayout->addWidget(m_dodEdit);
    QHBoxLayout* dodHeaderLayout = new QHBoxLayout();
    dodHeaderLayout->addWidget(new QLabel("DoD (完成定义):"));
    dodHeaderLayout->addStretch();
    dodHeaderLayout->addWidget(m_dodCharCountLabel);
    dodHeaderLayout->addWidget(m_dodTemplateBtn);
    m_dodTemplateBtn->setToolTip("插入DoD模板");
    m_dodTemplateBtn->setStyleSheet("QPushButton { padding: 4px 8px; font-size: 12px; }");
    connect(m_dodTemplateBtn, &QPushButton::clicked, this, &TaskEditDialog::onCopyDodTemplate);
    dodInputLayout->insertLayout(0, dodHeaderLayout);
    dodLayout->addLayout(dodInputLayout);
    formLayout->addRow("", dodLayout);

    // [FDD-2025-11] 阻塞点和产出（左右并排）
    QHBoxLayout* blockersArtifactsLayout = new QHBoxLayout();

    // 阻塞点
    QVBoxLayout* blockersLayout = new QVBoxLayout();
    blockersLayout->addWidget(new QLabel("阻塞点:"));
    m_blockersEdit->setPlaceholderText("描述当前遇到的阻塞问题...");
    m_blockersEdit->setMaximumHeight(70);
    blockersLayout->addWidget(m_blockersEdit);

    // 产出/证据
    QVBoxLayout* artifactsLayout = new QVBoxLayout();
    artifactsLayout->addWidget(new QLabel("产出/证据:"));
    m_artifactsSummaryEdit->setPlaceholderText("产出概述...");
    m_artifactsSummaryEdit->setMaximumHeight(40);
    artifactsLayout->addWidget(m_artifactsSummaryEdit);
    m_artifactsLinksEdit->setPlaceholderText("链接列表（每行一个）：\n- [标题](url)\n- https://...");
    m_artifactsLinksEdit->setMaximumHeight(30);
    artifactsLayout->addWidget(m_artifactsLinksEdit);

    blockersArtifactsLayout->addLayout(blockersLayout);
    blockersArtifactsLayout->addLayout(artifactsLayout);
    formLayout->addRow("", blockersArtifactsLayout);
    
    // 开始时间（添加快捷时间选择按钮）
    m_startTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm");
    m_startTimeEdit->setCalendarPopup(true);
    QHBoxLayout* startTimeLayout = new QHBoxLayout();
    startTimeLayout->addWidget(m_startTimeEdit);
    QPushButton* btnPickStartTime = new QPushButton("⏰");
    btnPickStartTime->setToolTip("快捷选择时间");
    btnPickStartTime->setFixedWidth(40);
    btnPickStartTime->setCursor(Qt::PointingHandCursor);
    btnPickStartTime->setStyleSheet(
        "QPushButton { "
        "  background-color: #4CAF50; "
        "  border: none; "
        "  border-radius: 4px; "
        "  font-size: 18px; "
        "}"
        "QPushButton:hover { "
        "  background-color: #66BB6A; "
        "}"
    );
    connect(btnPickStartTime, &QPushButton::clicked, this, &TaskEditDialog::onPickStartTime);
    startTimeLayout->addWidget(btnPickStartTime);
    startTimeLayout->addStretch();
    formLayout->addRow("开始时间*:", startTimeLayout);
    
    // 结束时间（添加快捷时间选择按钮）
    m_endTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm");
    m_endTimeEdit->setCalendarPopup(true);
    QHBoxLayout* endTimeLayout = new QHBoxLayout();
    endTimeLayout->addWidget(m_endTimeEdit);
    QPushButton* btnPickEndTime = new QPushButton("⏰");
    btnPickEndTime->setToolTip("快捷选择时间");
    btnPickEndTime->setFixedWidth(40);
    btnPickEndTime->setCursor(Qt::PointingHandCursor);
    btnPickEndTime->setStyleSheet(
        "QPushButton { "
        "  background-color: #4CAF50; "
        "  border: none; "
        "  border-radius: 4px; "
        "  font-size: 18px; "
        "}"
        "QPushButton:hover { "
        "  background-color: #66BB6A; "
        "}"
    );
    connect(btnPickEndTime, &QPushButton::clicked, this, &TaskEditDialog::onPickEndTime);
    endTimeLayout->addWidget(btnPickEndTime);
    endTimeLayout->addStretch();
    formLayout->addRow("结束时间*:", endTimeLayout);
    
    // 提醒设置
    QHBoxLayout* reminderLayout = new QHBoxLayout();
    m_reminderCheckBox->setChecked(false);
    m_reminderTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm");
    m_reminderTimeEdit->setCalendarPopup(true);
    m_reminderTimeEdit->setEnabled(false);
    reminderLayout->addWidget(m_reminderCheckBox);
    reminderLayout->addWidget(m_reminderTimeEdit);
    reminderLayout->addStretch();
    formLayout->addRow("提醒:", reminderLayout);
    
    mainLayout->addLayout(formLayout);
    
    // 如果是已完成的任务且有完成记录，显示完成记录
    if (!m_isNewTask && m_task.getStatus() == TaskStatus::Completed && !m_task.getCompletionNote().isEmpty()) {
        QGroupBox* completionGroup = new QGroupBox("完成记录", contentWidget);
        QVBoxLayout* completionLayout = new QVBoxLayout();
        
        QTextEdit* completionNoteView = new QTextEdit(contentWidget);
        completionNoteView->setPlainText(m_task.getCompletionNote());
        completionNoteView->setReadOnly(true);
        completionNoteView->setMaximumHeight(120);
        completionNoteView->setStyleSheet(
            "QTextEdit {"
            "    background-color: #f9f9f9;"
            "    border: 1px solid #e0e0e0;"
            "    border-radius: 4px;"
            "    padding: 8px;"
            "    color: #333;"
            "}"
        );
        
        // 完成时间
        QString completedTime = "完成时间: " + m_task.getCompletedTime().toString("yyyy-MM-dd HH:mm");
        QLabel* completedLabel = new QLabel(completedTime, contentWidget);
        completedLabel->setStyleSheet("color: #666; font-size: 12px; font-style: italic;");
        
        completionLayout->addWidget(completionNoteView);
        completionLayout->addWidget(completedLabel);
        completionGroup->setLayout(completionLayout);
        
        mainLayout->addWidget(completionGroup);
    }
    
    // 提示信息
    QLabel* hintLabel = new QLabel("* 为必填项", contentWidget);
    hintLabel->setStyleSheet("color: #999; font-size: 12px;");
    mainLayout->addWidget(hintLabel);
    
    mainLayout->addStretch();
    
    // 按钮布局
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_cancelBtn);
    buttonLayout->addWidget(m_saveBtn);
    
    m_saveBtn->setStyleSheet(
        "QPushButton {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    border: none;"
        "    padding: 8px 20px;"
        "    border-radius: 4px;"
        "    font-size: 14px;"
        "}"
        "QPushButton:hover { background-color: #45a049; }"
    );
    
    m_cancelBtn->setStyleSheet(
        "QPushButton {"
        "    background-color: #f1f1f1;"
        "    color: #333;"
        "    border: 1px solid #ccc;"
        "    padding: 8px 20px;"
        "    border-radius: 4px;"
        "    font-size: 14px;"
        "}"
        "QPushButton:hover { background-color: #e0e0e0; }"
    );
    
    mainLayout->addLayout(buttonLayout);

    // 将滚动区域添加到背景容器
    backgroundLayout->addWidget(scrollArea);
    
    // 连接信号
    connect(m_saveBtn, &QPushButton::clicked, this, &TaskEditDialog::onSave);
    connect(m_cancelBtn, &QPushButton::clicked, this, &TaskEditDialog::onCancel);
    connect(m_reminderCheckBox, &QCheckBox::toggled, this, &TaskEditDialog::onReminderToggled);
}

void TaskEditDialog::loadTask(const PlanTask& task)
{
    m_titleEdit->setText(task.getTitle());

    // [FDD-2025-11] 加载状态
    int statusIndex = m_statusCombo->findData(static_cast<int>(task.getStatus()));
    if (statusIndex >= 0) {
        m_statusCombo->setCurrentIndex(statusIndex);
    }

    m_descEdit->setPlainText(task.getScopeDescription());  // 范围/描述
    m_dodEdit->setPlainText(task.getDefinitionOfDone());   // DoD
    m_blockersEdit->setPlainText(task.getBlockers());      // 阻塞点

    // 产出/证据
    TaskArtifacts artifacts = task.getArtifacts();
    m_artifactsSummaryEdit->setPlainText(artifacts.summary);
    m_artifactsLinksEdit->setPlainText(artifacts.evidenceLinks.join("\n"));

    m_startTimeEdit->setDateTime(task.getStartTime());
    m_endTimeEdit->setDateTime(task.getEndTime());

    if (task.hasReminder()) {
        m_reminderCheckBox->setChecked(true);
        m_reminderTimeEdit->setDateTime(task.getReminderTime());
    }
}

PlanTask TaskEditDialog::getTask() const
{
    return m_task;
}

bool TaskEditDialog::validateInput()
{
    // 检查标题
    if (m_titleEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(const_cast<TaskEditDialog*>(this), "验证失败", "请输入任务标题");
        return false;
    }

    // [FDD-2025-11] 检查 DoD 字符数
    QString dod = m_dodEdit->toPlainText().trimmed();
    if (!dod.isEmpty() && dod.length() < 5) {
        QMessageBox::warning(const_cast<TaskEditDialog*>(this), "验证失败",
                             "完成定义（DoD）至少需要 5 个字符\n当前: " + QString::number(dod.length()) + " 个字符");
        return false;
    }

    // [FDD-2025-11] 检查状态与阻塞点的一致性
    TaskStatus status = static_cast<TaskStatus>(m_statusCombo->currentData().toInt());
    QString blockers = m_blockersEdit->toPlainText().trimmed();

    if ((status == TaskStatus::Done || status == TaskStatus::Completed) && !blockers.isEmpty()) {
        auto reply = QMessageBox::question(
            const_cast<TaskEditDialog*>(this),
            "确认保存",
            "任务状态为\"已完成\"，但仍存在阻塞点描述。\n是否仍要保存？",
            QMessageBox::Yes | QMessageBox::No
        );
        if (reply == QMessageBox::No) {
            return false;
        }
    }

    // 检查时间有效性
    QDateTime startTime = m_startTimeEdit->dateTime();
    QDateTime endTime = m_endTimeEdit->dateTime();

    if (startTime >= endTime) {
        QMessageBox::warning(const_cast<TaskEditDialog*>(this), "验证失败", "结束时间必须晚于开始时间");
        return false;
    }

    // 检查提醒时间
    if (m_reminderCheckBox->isChecked()) {
        QDateTime reminderTime = m_reminderTimeEdit->dateTime();
        if (reminderTime > startTime) {
            QMessageBox::warning(const_cast<TaskEditDialog*>(this), "验证失败", "提醒时间应该在开始时间之前");
            return false;
        }
    }

    return true;
}

void TaskEditDialog::onSave()
{
    if (!validateInput()) {
        return;
    }

    // 更新任务数据
    if (m_isNewTask) {
        m_task = PlanTask(QUuid::createUuid().toString(), m_titleEdit->text().trimmed());
    } else {
        m_task.setTitle(m_titleEdit->text().trimmed());
    }

    // [FDD-2025-11] 保存状态
    TaskStatus status = static_cast<TaskStatus>(m_statusCombo->currentData().toInt());
    m_task.setStatus(status);

    // 保存范围/描述（原来的 description 字段改为存储 scopeDescription）
    m_task.setScopeDescription(m_descEdit->toPlainText().trimmed());

    // [FDD-2025-11] 保存新字段
    m_task.setDefinitionOfDone(m_dodEdit->toPlainText().trimmed());
    m_task.setBlockers(m_blockersEdit->toPlainText().trimmed());

    // 保存产出/证据
    TaskArtifacts artifacts;
    artifacts.summary = m_artifactsSummaryEdit->toPlainText().trimmed();
    // 解析链接列表（按行分割）
    QString linksText = m_artifactsLinksEdit->toPlainText().trimmed();
    if (!linksText.isEmpty()) {
        artifacts.evidenceLinks = linksText.split('\n', Qt::SkipEmptyParts);
    }
    m_task.setArtifacts(artifacts);

    m_task.setStartTime(m_startTimeEdit->dateTime());
    m_task.setEndTime(m_endTimeEdit->dateTime());

    if (m_reminderCheckBox->isChecked()) {
        m_task.setReminder(true, m_reminderTimeEdit->dateTime());
    } else {
        m_task.setReminder(false);
    }

    m_result = 1;  // QDialog::Accepted
    emit accepted();
    close();
}

void TaskEditDialog::onCancel()
{
    m_result = 0;  // QDialog::Rejected
    emit rejected();
    close();
}

void TaskEditDialog::onReminderToggled(bool enabled)
{
    m_reminderTimeEdit->setEnabled(enabled);
    
    // 如果启用提醒，设置默认提醒时间为开始时间前10分钟
    if (enabled) {
        QDateTime reminderTime = m_startTimeEdit->dateTime().addSecs(-600);
        m_reminderTimeEdit->setDateTime(reminderTime);
    }
}

void TaskEditDialog::onPickStartTime()
{
    // 打开时间选择对话框
    TimePickerDialog picker(m_startTimeEdit->time(), this);
    picker.setDialogTitle("选择开始时间");
    
    if (picker.exec() == QDialog::Accepted) {
        QTime selectedTime = picker.selectedTime();
        
        // 更新日期时间编辑器的时间部分
        QDateTime currentDateTime = m_startTimeEdit->dateTime();
        currentDateTime.setTime(selectedTime);
        m_startTimeEdit->setDateTime(currentDateTime);
    }
}

void TaskEditDialog::onPickEndTime()
{
    // 打开时间选择对话框
    TimePickerDialog picker(m_endTimeEdit->time(), this);
    picker.setDialogTitle("选择结束时间");
    
    if (picker.exec() == QDialog::Accepted) {
        QTime selectedTime = picker.selectedTime();
        
        // 更新日期时间编辑器的时间部分
        QDateTime currentDateTime = m_endTimeEdit->dateTime();
        currentDateTime.setTime(selectedTime);
        m_endTimeEdit->setDateTime(currentDateTime);
    }
}

int TaskEditDialog::exec()
{
    show();
    raise();
    activateWindow();

    QEventLoop eventLoop;
    m_eventLoopStarted = true;
    connect(this, &TaskEditDialog::accepted, &eventLoop, &QEventLoop::quit);
    connect(this, &TaskEditDialog::rejected, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    return m_result;
}

void TaskEditDialog::onCopyDodTemplate()
{
    // [FDD-2025-11] 插入 DoD 默认模板
    QString dodTemplate =
        "□ 功能完成并自测通过\n"
        "□ 代码已提交并通过 Code Review\n"
        "□ 产出文档/截图已交付给相关人员\n"
        "□ 相关人员已通知";

    m_dodEdit->setPlainText(dodTemplate);
    m_dodEdit->setFocus();  // 聚焦到 DoD 编辑框
}

void TaskEditDialog::onStatusChanged(int index)
{
    // [FDD-2025-11] 状态改变时的处理逻辑
    Q_UNUSED(index);

    TaskStatus newStatus = static_cast<TaskStatus>(m_statusCombo->currentData().toInt());

    // 如果状态改为"已阻塞"，提示用户填写阻塞点
    if (newStatus == TaskStatus::Blocked && m_blockersEdit->toPlainText().trimmed().isEmpty()) {
        m_blockersEdit->setFocus();
        m_blockersEdit->setPlaceholderText("请描述当前的阻塞问题...");
        // 高亮阻塞点输入框（临时边框样式）
        m_blockersEdit->setStyleSheet(
            "QTextEdit { "
            "  background-color: #3c3c3c; "
            "  border: 2px solid #FF9800; "
            "  border-radius: 4px; "
            "  padding: 6px; "
            "  color: #e0e0e0; "
            "}"
        );
        // 1.5 秒后恢复样式
        QTimer::singleShot(1500, this, [this]() {
            m_blockersEdit->setStyleSheet("");
        });
    }

    // 如果状态改为"已完成"，且 DoD 为空，提示用户填写
    if ((newStatus == TaskStatus::Done || newStatus == TaskStatus::Completed) &&
        m_dodEdit->toPlainText().trimmed().isEmpty()) {
        m_dodEdit->setFocus();
        m_dodEdit->setPlaceholderText("请填写完成定义（DoD），至少 5 个字符...");
        // 高亮 DoD 输入框
        m_dodEdit->setStyleSheet(
            "QTextEdit { "
            "  background-color: #3c3c3c; "
            "  border: 2px solid #FF9800; "
            "  border-radius: 4px; "
            "  padding: 6px; "
            "  color: #e0e0e0; "
            "}"
        );
        QTimer::singleShot(1500, this, [this]() {
            m_dodEdit->setStyleSheet("");
        });
    }
}

